package com.example.demo.com.java8.optional;

import com.example.demo.com.java8.lambda.Apple;
import org.junit.Test;

import java.util.Optional;

/**
 * @author chengfei5
 * @date 2018/8/21
 */
public class OptionalTest {
    /**
     * of方法创建Optional实例
     */
    @Test
    public void test(){
        Optional<Apple> apple = Optional.of(new Apple());
        Apple apple1 = apple.get();
        System.out.println(apple1);
    }
    /**
     * empty方法创建空Optional实例
     */
    @Test
    public void test1(){
        Optional<Apple> apple = Optional.empty();
        Apple apple1 = apple.get();
        System.out.println(apple1);
    }
    /**
     * ofNullable 是of和empty的综合
     * isPresent，判断optional是否有值
     */
    @Test
    public void test2(){
        Optional<Apple> apple = Optional.ofNullable(null);
        //isPresent，判断optional是否有值
        if(apple.isPresent()){
            System.out.println(apple.get());
        }
        Apple apple1 = apple.orElse(new Apple(120,"yellow"));
        System.out.println(apple1);
    }

    /**
     * orElseGet(Supplier<T> s) 如果包含值，返回，如果不包含，返回s获取的值
     */
    @Test
    public void test3(){
        Optional<Apple> apple = Optional.ofNullable(null);
        Apple apple1 = apple.orElseGet(()->new Apple(110,"green"));
        System.out.println(apple1);

    }

    /**
     * map:如果
     */
    @Test
    public void test4(){
        Optional<Apple> apple = Optional.ofNullable(new Apple(110,"green"));
        Optional<String> s = apple.map(e -> e.getColor());
        System.out.println(s);
    }

    @Test
    public void test5(){
       Person person = new Person();
       String carName = getCarName(person);
        System.out.println(carName);
        System.out.println(getCarName2(null));
    }
    @Test
    public void test6(){
        Person person = new Person();
        Car car = new Car("保时捷");
        person.setCar(car);

        getCarName3(person);
//        getCarName3(null);
    }
    /**
     * 获取一个人开什么车
     */
    private String getCarName(Person person){
        //java8以前
        String carName = "马自达cx-5";
        if(person == null){
            return carName;
        }
        if(person.getCar() == null){
            return carName;
        }
        return person.getCar().getCarName();
    }

    /**
     * 获取一个人开什么车
     */
    private String getCarName2(Person person){
        //java8
        /**
         * map里面传入的是函数，可以进行各种操作
         */
       return Optional.ofNullable(person)
                .map(p->p.getCar())
                .map(c->c.getCarName())
                .orElse("宝马x3");



    }

    /**
     * 获取一个人开什么车
     */
    private void getCarName3(Person person){
        //java8
        /**
         * map里面传入的是函数，可以进行各种操作
         */
        Optional.ofNullable(person)
                .map(p->p.getCar())
                .map(c->c.getCarName())
                .ifPresent(s -> System.out.print(s));



    }
}
